<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 部门树 -->
      <el-col :span="4" style="">
        <el-card shadow="hover">
          <el-tree class="mt-2" ref="deptTreeRef" node-key="id"
                   :data="deptOptions"
                   :props="{ label: 'deptName', children: 'children' }"
                   :expand-on-click-node="false"
                   :filter-node-method="filterNode"
                   highlight-current
                   default-expand-all
                   @node-click="handleNodeClick"/>
        </el-card>
      </el-col>

      <el-col :span="20" :gutter="20">
        <!-- 领导 -->
        <el-row :gutter="10" class="mb8">
          <el-col>
            <div class="leader">
              <img :src=this.leaterInfo.imgUrl class="imgs">
              <el-row class="wenzi">
                <el-col :span="20">
                  {{ leaterInfo.nickName }}
                </el-col>
              </el-row>
              <el-row class="wenzi2">
                <el-col :span="20">
                  {{ leaterInfo.deptName }}
                </el-col>
              </el-row>
              <div class="leaderZhiyin"></div>
            </div>
          </el-col>
          <!--          <el-col :span="14">-->
          <!--            <div class="jieshao">-->
          <!--              <span style="position:absolute;left: 30px">-->
          <!--                职位：国家主席-->
          <!--              </span>-->
          <!--              <br>-->
          <!--              <span style="position:absolute;left: 30px">-->
          <!--                电话：111111111-->
          <!--              </span>-->
          <!--              <br>-->
          <!--              <span style="position:absolute;left: 30px">-->
          <!--                工作职责：-->
          <!--              </span>-->
          <!--            </div>-->
          <!--          </el-col>-->
        </el-row>

        <div class="fenge"></div>
        <!-- 手下 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="4" v-for="t in staffInfo">
            <a :href="'/chy/property/estate/user?deptId='+t.deptId+'&estateId='+queryParams.estateId">
              <div class="staff">
                <img :src="t.imgUrl" class="imgs">
                <el-row class="wenzi">
                  <el-col :span="20">
                    {{ t.nickName }}
                  </el-col>
                </el-row>
                <el-row class="wenzi2">
                  <el-col :span="20">
                    {{ t.deptName }}
                  </el-col>
                </el-row>

                <div class="staffZhiyin"></div>
              </div>
            </a>
          </el-col>

        </el-row>
      </el-col>
    </el-row>


    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer"
                          placeholder="选择上级部门"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称" size="mini"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="部门职能" prop="deptName">
              <el-select v-model="form.eventTypeIds" multiple placeholder="请选择部门职能" size="mini">
                <el-option v-for="type in eventTypeOption"
                           :key="type.id"
                           :label="type.eventType"
                           :value="type.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" size="mini"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" size="mini"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开启工作日志" prop="isOpenLog">
              <el-radio-group v-model="form.isOpenLog" size="mini">
                <el-radio :value="0" :label="0">关闭</el-radio>
                <el-radio :value="1" :label="1">开启</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="日志级别" prop="logLevel">
              <el-radio-group v-model="form.logLevel" size="mini">
                <el-radio :value="1" :label="1">高级</el-radio>
                <el-radio :value="2" :label="2">普通</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" size="mini"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in statusOptions"
                          :key="dict.dictValue"
                          :label="dict.dictValue">{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="submitForm">确 定</el-button>
        <el-button @click="cancel" size="mini">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="titleUser" :visible.sync="openUser" width="700px" append-to-body>
      <el-form ref="form" :model="formUser" :rules="rules" label-width="110px">
        <el-row v-if="formUser.sysUserId == undefined">
          <el-col :span="12">
            <el-form-item label="登录名" prop="sysUserName">
              <el-input v-model="formUser.sysUserName" placeholder="请输入登录名" maxlength="30" size="mini"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="formUser.password" placeholder="请输入用户密码" type="password"
                        maxlength="20" show-password size="mini"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phoneNum">
              <el-input v-model="formUser.phoneNum" placeholder="请输入手机号码" maxlength="11" size="mini"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formUser.email" placeholder="请输入邮箱" maxlength="50" size="mini"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" v-if="formUser.deptId !== 0">
            <el-form-item label="所属部门" prop="deptId">
              <treeselect v-model="formUser.deptId" :options="deptOptions" :normalizer="normalizer"
                          placeholder="选择所属部门"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名">
              <el-input v-model="formUser.sysNickName" placeholder="请输入用户名" maxlength="50" size="mini"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="formUser.sex" placeholder="请选择" size="mini">
                <el-option v-for="dict in sexOptions"
                           :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="formUser.state" size="mini">
                <el-radio :value="0" :label="0">未启用</el-radio>
                <el-radio :value="1" :label="1">已启用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否是经理">
              <el-radio-group v-model="formUser.isManager" size="mini">
                <el-radio :value="0" :label="0">否</el-radio>
                <el-radio :value="1" :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="微信用户" prop="nickName">
              <el-input v-model="formUser.nickName" readonly placeholder="请输入微信编号" size="mini">
                <template slot="append">
                  <el-button @click="bandWxUser" size="mini">重新绑定</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="formUser.remark" type="textarea" placeholder="请输入内容" size="mini"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="submitFormUser">确 定</el-button>
        <el-button @click="cancelUser" size="mini">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="titleBandWxUser" :visible.sync="openBandWxUser" width="500px" append-to-body>
      <el-form ref="form" :model="queryParamsWxUser" label-width="170px">
        <el-form-item label="微信昵称/手机号/编号" prop="nickName">
          <el-input v-model="queryParamsWxUser.nickName" placeholder="请输入微信昵称/手机号/编号" size="mini"
                    maxlength="30" @onblur="getListMpSearch" clearable>
            <template slot="append">
              <el-button @click="getListMpSearch" size="mini">搜索</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="微信用户昵称" prop="userId" v-if="wxUserOptions.length > 0">
          <div class="wx-user">
            <el-radio-group v-model="queryParamsWxUser.userId" @change="changeWxUser($event)">
              <el-row v-for="(wxUser,index) in wxUserOptions">
                <el-col :span="24">
                  <el-radio :label="wxUser.id" :value="wxUser.id">
                    <a :href="wxUser.faceUrl" style="color: #42b983" target="_blank">
                      <img :src="wxUser.faceUrl" alt="点击打开" class="el-avatar">
                    </a> {{ wxUser.nickName }}({{ wxUser.phoneNum != null ? wxUser.phoneNum : '' }})
                  </el-radio>
                </el-col>
              </el-row>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="submitEstateUser">确 定</el-button>
          <el-button @click="openBandWxUser = false" size="mini">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import {listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild, listDepts} from "@/api/system/dept";
import {listType,} from "@/api/module/event/type";
import {listByNickName} from "@/api/module/wx/user";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {addUser, delUser, getUser, listUser, updateUser} from "@/api/module/estate/user";

export default {
  name: "Dept",
  components: {Treeselect},
  data() {
    return {
      activeName: '1',
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      eventTypeOption: [],
      userList: [],
      sexOptions: [],
      wxUserOptions: [],
      // 弹出层标题
      title: "",
      titleUser: "",
      titleBandWxUser: "",
      leaterInfo: [],
      staffInfo: [],
      // 是否显示弹出层
      open: false,
      openUser: false,
      openBandWxUser: false,
      // 状态数据字典
      statusOptions: [],
      bandUserTypeOptions: [],
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined,
        estateId: undefined,
        eventType: undefined,
      },
      // 查询参数
      queryParamsUser: {
        pageNum: 1,
        pageSize: 10,
        estateId: undefined,
        deptId: undefined,
        nickName: undefined,
      },
      queryParamsWxUser: {
        nickName: undefined,
        userId: undefined,
        platform: 'wxwork',// 只查询 工作端  彩恒云的 用户
      },
      formUserMp: {
        id: undefined,
        estateId: undefined,
        nickName: undefined,
        faceUrl: undefined,
        sysUserId: undefined,
        userId: undefined,
        userType: 3
      },
      chooseDeptId: undefined,
      total: 0,
      // 表单参数
      form: {},
      // 表单参数
      formUser: {},
      // 表单校验
      rules: {
        parentId: [
          {required: true, message: "上级部门不能为空", trigger: "blur"}
        ],
        deptName: [
          {required: true, message: "部门名称不能为空", trigger: "blur"}
        ],
        orderNum: [
          {required: true, message: "显示排序不能为空", trigger: "blur"}
        ],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.queryParams.estateId = this.$route.query.estateId ? parseInt(this.$route.query.estateId) : 0;
    this.queryParams.propertyId = this.$route.query.pId ? parseInt(this.$route.query.pId) : 0;
    this.queryParamsUser.estateId = this.$route.query.estateId ? parseInt(this.$route.query.estateId) : 0;
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("band_dept_user_type").then(response => {
      this.bandUserTypeOptions = response.data;
    });
    this.getDicts("sys_user_sex").then(response => {
      this.sexOptions = response.data;
    });

    this.getEventList();

    listDepts(this.queryParams).then(response => {
      this.deptOptions = this.handleTree(response.data, "deptId");
    });
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      listDept(this.queryParams).then(response => {
        this.leaterInfo = response.leaderInfo;
        this.staffInfo = response.staffInfo;
        this.loading = false;
        console.log(response);
      });

    },
    /** 查询用户列表 */
    getUserList() {
      this.loading = true;
      listUser(this.queryParamsUser).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
          if (this.chooseDeptId == undefined) {
            this.chooseDeptId = this.userList[0].deptId;
          }
        }
      );
    },
    /** 查询事件计划类型列表 */
    getEventList() {
      listType({}).then(response => {
        this.eventTypeOption = response.rows;
      });
    },
    handleClick(val) {
      console.log('handleClick', val);
      this.activeName = val.name;
      this.queryParamsUser.pageNum = 1;
      if (val.name == '0') {
        this.queryParamsUser.deptId = 0;
      } else {
        this.queryParamsUser.deptId = this.chooseDeptId;
      }

      this.getUserList();
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      console.log('handleNodeClick', data)
      this.queryParamsUser.deptId = data.deptId;
      this.chooseDeptId = data.deptId;
      window.location.replace('https://www.caihengyun.com/chy/property/estate/user?deptId=' + data.deptId + '&estateId=' + this.queryParams.estateId);
      console.log('chooseDeptId', this.chooseDeptId)
      this.getUserList();
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    bandWxUser(row) {
      this.openBandWxUser = true;
      this.titleBandWxUser = "绑定管理员微信";
      console.log('bandWxUser', row);
      this.queryParamsWxUser.nickName = undefined;
      this.queryParamsWxUser.userId = undefined;
      this.wxUserOptions = [];

      // this.getEstateUserList(row.userId);
      // this.formUserMp.id = row.estateUserId;
      // this.formUserMp.sysUserId = row.userId;
    },
    changeWxUser(e, index) {
      console.log('changeWxUser e ', e)
      console.log('changeWxUser index', index)
    },
    getListMpSearch() {
      // this.queryParamsWxUser.nickName = this.form.userNo;
      listByNickName(this.queryParamsWxUser).then(response => {
        console.log('getListMpSearch', response.data);
        this.wxUserOptions = response.data;
      });
    },
    submitEstateUser() {
      if (this.queryParamsWxUser.userId != undefined) {
        this.formUser.userId = this.queryParamsWxUser.userId;
        this.openBandWxUser = false;
        for (let index in this.wxUserOptions) {
          let wxUser = this.wxUserOptions[index];
          if (wxUser.id == this.queryParamsWxUser.userId) {
            console.log('wxUser', wxUser)
            this.formUser.nickName = wxUser.nickName;
          }
        }
      } else {
        this.msgError("请选择用户昵称");
      }
      // this.formUser.userId = this.queryParamsWxUser.userId;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    cancelUser() {
      this.openUser = false;
      this.resetUser();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        propertyId: this.queryParams.propertyId,
        estateId: this.queryParams.estateId,
        eventType: undefined,
        deptName: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        isOpenLog: undefined,
        logLevel: undefined,
        status: "0",
        eventTypeIds: [],
      };
      this.resetForm("form");
    },
    // 表单重置
    resetUser() {
      this.formUser = {
        userId: undefined,
        roleId: 4,
        estateId: this.queryParams.estateId,
        deptId: undefined,
        userType: 3,
        nickName: undefined,
        sysNickName: undefined,
        password: undefined,
        phoneNum: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        isManager: undefined,
        sysUserName: undefined,
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAddUser() {
      this.resetUser();
      this.openUser = true;
      this.formUser.estateId = this.queryParamsUser.estateId;
      this.formUser.deptId = this.queryParamsUser.deptId;
    },
    /** 修改按钮操作 */
    handleUpdateUser(row) {
      this.resetUser();
      const userId = row.id || this.ids;
      getUser(userId).then(response => {
        this.formUser = response.data;
        this.postOptions = response.data.posts;
        this.roleOptions = response.data.roles;
        this.formUser.postIds = response.data.postIds;
        this.formUser.roleIds = response.data.roleIds;
        this.openUser = true;
        this.titleUser = "修改用户";
        this.formUser.password = "";
      });
    },
    /** 删除按钮操作 */
    handleDeleteUser(row) {
      const userIds = row.id || this.ids;
      this.$confirm('是否确认删除用户编号为"' + userIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delUser(userIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },

    handleQueryNickName() {
      console.log("1", this.queryParamsUser)
      this.activeName = "1";
      this.getUserList();
      console.log(this.queryParamsUser)
    },
    resetQueryNickName() {
      this.queryParamsUser.nickName = undefined;
      this.handleQueryNickName();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      console.log('row', row)
      if (row != undefined) {
        this.form.parentId = row.deptId;
      } else {
        this.form.parentId = 0;
      }

      this.open = true;
      this.title = "添加部门";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getDept(row.deptId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改部门";
      });
      listDeptExcludeChild(row.deptId).then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form)
          if (this.form.deptId != undefined) {
            updateDept(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDept(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.deptName + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delDept(row.deptId);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    /** 提交按钮 */
    submitFormUser() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.formUser.id !== undefined) {
            updateUser(this.formUser).then(response => {
              this.msgSuccess("修改成功");
              this.openUser = false;
              this.getUserList();
            });
          } else {
            addUser(this.formUser).then(response => {
              this.msgSuccess("新增成功");
              this.openUser = false;
              this.getUserList();
            });
          }
        }
      });
    },
  }
};
</script>
<style>
.leader {
  width: 170px;
  height: 300px;
  background-color: #eeeeee;
  position: relative;
  border-style: solid;
  border-width: 1px;
  border-radius: 10px;
  border-color: #cccccc;
  margin-left: 600px;
  margin-bottom: 70px;
  display: block;
}

.imgs {
  width: 150px;
  position: absolute;
  right: 10px;
  top: 10px;
  height: 220px;
  border-radius: 5px
}

.wenzi {
  position: absolute;
  left: 15px;
  bottom: 35px;
  font-size: 20px;
  width: 100%
}

.wenzi2 {
  position: absolute;
  left: 15px;
  bottom: 10px;
  font-size: 20px;
  width: 100%
}

.staff {
  width: 170px;
  height: 300px;
  margin-top: 70px;
  background-color: #eeeeee;
  position: relative;
  border-style: solid;
  border-width: 1px;
  border-radius: 10px;
  border-color: #cccccc;
  float: top;
  margin-left: 3%;
}

.fenge {
  width: 100%;
  border-bottom: 10px solid #cccccc
}

.leaderZhiyin {
  height: 80px;
  width: 10px;
  background-color: #cccccc;
  text-align: center;
  margin-top: 299px;
  left: 90px;
  position: absolute;
  /*z-index:-1*/
}

.staffZhiyin {
  height: 80px;
  width: 10px;
  background-color: #cccccc;
  text-align: center;
  margin-top: -80px;
  left: 90px;
  position: absolute;
  /*z-index:-1*/
}

.jieshao {
  width: auto;
  height: 280px;
  background-color: #eeeeee;
  border-style: solid;
  border-width: 1px;
  border-radius: 10px;
  border-color: #cccccc;
  position: relative;
}
</style>
